Consider this function that swaps its two integer arguments:
void swap(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}
If we also had to swap floats, longs, Strings, Sets, and FileSystems, we'd get pretty tired of coding lines that look almost identical except for the type. Mindless repetition is an ideal job for a computer, hence a function template:
template<class T>
void swap(T& x, T& y)
{
T tmp = x;
x = y;
y = tmp;
}
Every time we used 'swap()' with a given pair of types, the compiler will go to the above definition and will create yet another 'template function' as an instantiation of the above. Ex:
main()
{
int i,j; /*...*/ swap(i,j); //instantiates a swap for 'int'
float a,b; /*...*/ swap(a,b); //instantiates a swap for 'float'
char c,d; /*...*/ swap(c,d); //instantiates a swap for 'char'
String s,t; /*...*/ swap(s,t); //instantiates a swap for 'String'
}
(note: a 'template function' is the instantiation of a 'function template').